package com.greatwqs.wmall.common.provider.utils;

import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate with default timeOut
 *
 * @author wang-qingsong
 * @since 2021/11/12
 */
public class RestTemplateUtil {

    // HTTP timeout (in milliseconds).
    public static final int HTTP_CONNECTION_TIMEOUT = 1000 * 5;
    // api request time out: 60 second.
    public static final int HTTP_READ_TIMEOUT_API = 1000 * 60;
    // download file maybe long: 100 second.
    public static final int HTTP_READ_TIMEOUT_DOWNLOAD = 1000 * 100;

    public static RestTemplate restTemplate() {
        return restTemplateWithTimeout(HTTP_CONNECTION_TIMEOUT, HTTP_READ_TIMEOUT_API);
    }

    public static RestTemplate restTemplateDownload() {
        return restTemplateWithTimeout(HTTP_CONNECTION_TIMEOUT, HTTP_READ_TIMEOUT_DOWNLOAD);
    }

    private static RestTemplate restTemplateWithTimeout(int connectionTimeout, int readTimeout) {
        RestTemplate restTemplate = new RestTemplate();
        // SimpleClientHttpRequestFactory: implementation that uses standard JDK facilities.
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(connectionTimeout);
        requestFactory.setReadTimeout(readTimeout);
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }
}
